<template>
  <div ref="LoginBox" class="login" id="login">
    <div class="loginBox">
      <div v-show="!isPassword" class="loginBox2">
        <div class="logo">
          <img class="logoImg" src="../../assets/home/logoText.png" alt="">
          <!-- <div class="blueColor">开放蓝天</div> -->
        </div>
        <div class="loginTitle">
          <button :class="{ 'blueColor': true, 'orangeColor': isLogin }" @click="dialogTableVisible=false;isLogin = true">登录</button>
          <button :class="{ 'blueColor': true, 'orangeColor': !isLogin }" @click="dialogTableVisible=false;isLogin = false">注册</button>
        </div>
        <div class="otherLogo">
          <img src="../../assets/home/qqlogo.png" alt="">
          <img src="../../assets/home/wx_logo.png" alt="" @click="onWeiXinLogin">
          <a href="https://api.weibo.com/oauth2/authorize?client_id=2381070913&response_type=code&redirect_uri=http://openbluesky.cn/xman/auth2.0/weibo/success/weibo"><img src="../../assets/home/wblogo.png" alt=""></a>
        </div>
        <div class="lineBox">
          <div class="line"></div>
          <div class="lineOr">or</div>
          <div class="line"></div>
        </div>
        <div v-if="dialogTableVisible" @click.stop class="iframe-wrapper">
          <iframe  sandbox="allow-scripts allow-top-navigation allow-same-origin"  :src="url" class="iframe" @load="handleIframeLoad"></iframe>
          <button class="cancel-button" @click.self="closeIframe">X</button>
        </div>
        <div class="loginForm">
          <div v-show="isLogin" class="loginData">
            <el-form ref="ruleForm" :model="loginForm" status-icon :rules="rules" label-width="100px"
                     class="demo-ruleForm">
              <el-form-item prop="userPhone">
                <el-input v-model="loginForm.userPhone" type="text" autocomplete="off" placeholder="用户名/手机号码" />
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" autocomplete="off" placeholder="密码"
                          @keyup.enter="login" />
              </el-form-item>
              <el-form-item>
                <el-button class="loginBtn blueBgc" type="primary" @click="login()">
                  <img class="loginBtn_img" src="../../assets/home/anquan1.png" alt="">
                  安全登录</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div v-show="!isLogin" class="loginData enroll">
            <el-form ref="ruleForm" :model="enroll" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
              <el-form-item prop="userName" v-show="!enroll.openid">
                <el-input v-model="enroll.userName" type="text" autocomplete="off" placeholder="输入英文用户名" />
              </el-form-item>
              <el-form-item prop="phone">
                <el-input v-model="enroll.phone" type="text" autocomplete="off" placeholder="绑定手机" />
              </el-form-item>
              <el-form-item prop="password" v-show="!enroll.openid">
                <el-input v-model="enroll.password" type="password" autocomplete="off" placeholder="密码最小长度为6" />
              </el-form-item>
              <el-form-item prop="password_2" v-show="!enroll.openid">
                <el-input v-model="enroll.password_2" type="password" autocomplete="off" placeholder="再次输入密码" />
              </el-form-item>
              <el-form-item prop="captcha">
                <el-input v-model="enroll.captcha" class="borderZero" type="text" autocomplete="off"
                          placeholder="手机验证码" />
                <el-button ref="enrollCaptcha" class="borderZero captchaBtn" type="primary"
                           @click="getCaptcha('enrollCaptcha')">
                  <span ref="enrollCaptchaText">发送验证码</span>
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button class="loginBtn blueBgc" type="primary" @click="goregister">
                  <img class="loginBtn_img" src="../../assets/home/zhiwen.png" alt="">
                  立即注册</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <button class="forget" @click="isPassword = true">忘记密码?</button>
      </div>
      <div v-show="isPassword" class="resetPassword loginBox2">
        <div class="logo resetTitle">
          <div>重置密码</div>
        </div>
        <div class="loginForm">
          <div class="loginData">
            <el-form ref="ruleForm" :model="reset" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
              <el-form-item prop="phone">
                <el-input v-model="reset.phone" type="text" autocomplete="off" placeholder="输入手机号码" />
              </el-form-item>
              <el-form-item prop="captcha">
                <el-input v-model="reset.captcha" class="borderZero" type="text" autocomplete="off" placeholder="手机验证码" />
                <el-button ref="resetCaptcha" class="borderZero captchaBtn" type="primary"
                           @click="getCaptcha('resetCaptcha')">
                  <span ref="resetCaptchaText">发送验证码</span>
                </el-button>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="reset.password" type="password" autocomplete="off" placeholder="输入新密码" />
              </el-form-item>
              <el-form-item>
                <el-button class="loginBtn blueBgc" type="primary" @click="resetPassword">
                  <img class="loginBtn_img" src="../../assets/home/zhiwen.png" alt="">
                  重置密码</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <button class="forget" @click="isPassword = false">返回登录</button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import loginApi from '@/api/login'
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { defineEmits } from 'vue'
import { setToken } from '@/utils/index'
import brodacast from './brodacast'
import useUserStore from '@/stores/user'

// 用于子组件发送emit事件给父组件
// 设置事件名
const emit = defineEmits(['closeLogin'])

const route = useRoute()
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const userStore = useUserStore()


// 校验规则
const valiUserPhone = (rule: any, value: any, callback: any) => {
  console.log('value', value)
  if (!value) {
    callback(new Error('请输入用户名/手机号码'))
  } else {
    // if (this.ruleForm.checkPass !== '') {
    //   this.$refs.ruleForm.validateField('checkPass')
    // }
    callback()
  }
}
const valiUserName = (rule: any, value: any, callback: any) => {
  console.log('value', value)
  const reg = /^[a-zA-Z]+$/
  if (!value) {
    callback(new Error('请输入英文用户名'))
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确的英文用户名'))
  } else {
    callback()
  }
}
const valiPhone = (rule: any, value: any, callback: any) => {
  console.log('value', value)
  const reg = /^[1][3, 4, 5, 6, 7, 8, 9][0-9]{9}$/
  if (!value) {
    callback(new Error('请输入手机号码'))
  } else if (!reg.test(value)) {
    callback(new Error('输入正确的手机号码'))
  } else {
    callback()
  }
}
const valiPassword = (rule: any, value: any, callback: any) => {
  console.log('value', value)
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码最小长度为6!'))
  } else {
    callback()
  }
}
const valiPassword2 = (rule: any, value: any, callback: any) => {
  console.log('value', value)
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (value !== enroll.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}
const valiCaptcha = (rule: any, value: any, callback: any) => {
  console.log('value', value)
  if (!value) {
    return callback(new Error('验证码不能为空'))
  }
  // setTimeout(() => {
  //   console.log(Number.isInteger(value))
  //   if (!Number.isInteger(value)) {
  //     callback(new Error('请输入数字值'))
  //   } else {
  //     callback()
  //   }
  // }, 1000)
}

//登录数据
const loginForm = reactive({
  userPhone: '',
  password: ''
})
//注册数据
const enroll = reactive({
  userName: '',
  phone: '',
  password: '',
  password_2: '',
  captcha: '',
  openid: ''
})
const bindData = reactive({
  openid: '',
  source: ''
})
function goregister() {
  if (enroll.openid) {
    loginApi.bindPhone({
      phone: enroll.phone,
      code: enroll.captcha,
      ...bindData
    }).then(res => {
      ElMessage({
        message: '注册成功',
        type: 'success',
        duration: 3000,
        customClass: 'message-wrap'
      })
      setToken(res.token)
      emit('closeLogin')
    })
  }
  else {
    loginApi.register({
      ...enroll,
      "identifyCode": enroll.captcha,
      "userAccount": enroll.userName,
    }).then(res => {
      ElMessage({
        message: '注册成功',
        type: 'success',
        duration: 3000,
        customClass: 'message-wrap'
      })
      setToken(res.token)
      emit('closeLogin')
    })
  }
}
const token=ref<string>('')
onMounted(() => {
  // 微博登录
  if (route.query.source === 'weibo') {
    if (!route.query.isPhone) {
      ElMessage({
        message: '请先绑定手机',
        type: 'warning',
        duration: 3000,
        customClass: 'message-wrap'
      })
      isLogin.value = false
      bindData.openid = route.query.openid as string
      bindData.source = route.query.source
      enroll.openid = route.query.openid as string
      token.value = route.query.token as string
    }
  } else  if (route.query.source == "wechat_open") {
      dialogTableVisible.value = false
      bindData.openid = route.query.openid as string
      bindData.source = route.query.source
      enroll.openid = route.query.openid as string
      token.value = route.query.token as string
      console.log(route.query.isPhone)
      // 微信登录成功,关闭通知
      if (route.query.isPhone) {
        ElMessage({
          message: '登录成功',
          type: 'success',
          duration: 3000,
          customClass: 'message-wrap'
        })
        setToken(token.value)
        emit('closeLogin')
      } else {
        ElMessage({
          message: '请先绑定手机',
          type: 'warning',
          duration: 3000,
          customClass: 'message-wrap'
        })
        enroll.openid = route.query.openid as string
        isLogin.value = false
      }
    }
})

// 垂直数据
const reset = reactive({
  phone: '',
  captcha: '',
  password: ''
})

function resetPassword() {
  let resetobj = {
    phone: reset.phone,
    newPassword: reset.password,
    code: reset.captcha,
  }
  loginApi.resetPassword(resetobj).then(res => {
    isPassword.value = false
    ElMessage({
      message: '重置密码成功',
      type: 'success',
      duration: 3000,
      customClass: 'message-wrap'
    })
  })
}


//规则校验
const rules = reactive({
  userPhone: [{ validator: valiUserPhone, trigger: 'blur' }],
  userName: [{ validator: valiUserName, trigger: 'blur' }],
  phone: [{ validator: valiPhone, trigger: 'blur' }],
  password: [{ validator: valiPassword, trigger: 'blur' }],
  password_2: [{ validator: valiPassword2, trigger: 'blur' }],
  captcha: [{ validator: valiCaptcha, trigger: 'blur' }]
})

let isLogin = ref(true)// 用于切换登录和注册页
let isPassword = ref(false)// 用于切换登录/注册和垂直密码页面
let isGetCaptcha_enroll = ref(false)// 点击获取验证码之后变为true，用于判断是否多次点击发送验证码，防止多次点击———注册页面的验证码
let isGetCaptcha_reset = ref(false)// 点击获取验证码之后变为true，用于判断是否多次点击发送验证码，防止多次点击———重置密码页面的验证码
let verificationTime_enroll = ref(60)// 验证码倒计时———注册页面的验证码
let verificationTime_reset = ref(60)// 验证码倒计时———重置密码页面的验证码
// ref获取dom
const enrollCaptchaText = ref(null)
const enrollCaptcha = ref(null)
const resetCaptchaText = ref(null)
const resetCaptcha = ref(null)
const LoginBox = ref(null)
// const rules = reactive<FormRules>({
//   pass: [{ validator: validatePass, trigger: 'blur' }],
//   checkPass: [{ validator: validatePass2, trigger: 'blur' }],
//   age: [{ validator: checkAge, trigger: 'blur' }],
// })

// 重新获取等待时间———重置注册页面的验证码
const getVerificationTime_enroll = () => {
  loginApi.sendCode(enroll.phone).then(res => {
    console.log(res)
  })
  isGetCaptcha_enroll.value = true
  for (let i = 0; i < 60; i++) {
    setTimeout(() => {
      verificationTime_enroll.value = verificationTime_enroll.value - 1
      enrollCaptchaText.value.innerText = verificationTime_enroll.value
      enrollCaptcha.value.$el.style.backgroundColor = '#bdbdbd'
      enrollCaptcha.value.$el.style.borderColor = '#bdbdbd'
      if (verificationTime_enroll.value === 0) {
        verificationTime_enroll.value = 60
        isGetCaptcha_enroll.value = false
        enrollCaptchaText.value.innerText = '重新获取'
        enrollCaptcha.value.$el.style.backgroundColor = '#ff492c'
        enrollCaptcha.value.$el.style.borderColor = '#ff492c'
      }
    }, 1000 * i)
  }
}
// 重新获取等待时间———重置密码页面的验证码
const getVerificationTime_reset = () => {
  loginApi.sendCode(reset.phone).then(res => {
    console.log(res)
  })
  isGetCaptcha_reset.value = true
  for (let i = 0; i < 60; i++) {
    setTimeout(() => {
      verificationTime_reset.value = verificationTime_reset.value - 1
      resetCaptchaText.value.innerText = verificationTime_reset.value
      resetCaptcha.value.$el.style.backgroundColor = '#bdbdbd'
      resetCaptcha.value.$el.style.borderColor = '#bdbdbd'
      if (verificationTime_reset.value === 0) {
        verificationTime_reset.value = 60
        isGetCaptcha_reset.value = false
        resetCaptcha.value.innerText = '重新获取'
        resetCaptcha.value.$el.style.backgroundColor = '#ff492c'
        resetCaptcha.value.$el.style.borderColor = '#ff492c'
      }
    }, 1000 * i)
  }
}
// 点击获取验证码
const getCaptcha = (type: string) => {
  if (type === 'enrollCaptcha' && !isGetCaptcha_enroll.value) {
    getVerificationTime_enroll()
  } else if (type === 'resetCaptcha' && !isGetCaptcha_reset.value) {
    getVerificationTime_reset()
  }
}
// 登录
const login = () => {
  loginApi.login({
    userAccount: loginForm.userPhone,
    password: loginForm.password
  }).then(res => {
    ElMessage({
      message: '登录成功',
      type: 'success',
      duration: 3000,
      customClass: 'message-wrap'
    })
    setToken(res.token)
    emit('closeLogin')
    userStore.setUserId(res.id as string)
  })
}
const url=ref<string>("")
const dialogTableVisible=ref<Boolean>(false)
const closeIframe=()=> {
  dialogTableVisible.value=false
}

const showIframe = ref(false)
/**
 * 触发微信登录
 */
const onWeiXinLogin = async () => {
  dialogTableVisible.value=true;
    // 1. 通过微信登录前置数据获取接口，获取登录数据
    const data: any = await loginApi.getWXLoginData()
    url.value=data.url
    console.log("触发微信登录")

    // 等待扫码登录成功通知
    const { token, isPhone, openid, source } = await brodacast.wait()

  console.log("微信结束")
}

</script>

<style lang="scss" scoped>
.blueColor {
  color: #202123;
}

.orangeColor {
  color: #ff492c;
}

.blueBgc {
  background-color: #202123;
  border-color: #202123;
}

// .login {
//   // position: absolute;
//   // filter: blur(10px);
//   // width: 100%;
//   // height: 100%;
// }

.login::after {
  content: '';
  width: 100%;
  height: 100%;
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
  // background-image: url(../../assets/home/v_phone.png);
  // background-color: #409eff;
  backdrop-filter: blur(10px);
  z-index: 9998;
}

.loginBox {
  width: 100%;
  height: 100%;
  background-color: #fff;
  // border-radius: 10px;
  position: fixed;
  // left:0;
  // right:0;
  // top: 18%;
  // margin: 0 auto;
  z-index: 9999;
}

.loginBox2 {
  width: 90%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}

.logo {
  margin: 40px 0;
  // height: 40px;
  font-size: 30px;
  display: flex;
  justify-content: center;
}

.logoImg {
  height: 3rem;
}

.loginTitle {
  width: 50%;
  margin: 0px auto;
  font-size: 17px;
  display: flex;
  justify-content: space-evenly;

  button {
    border: 0;
    outline: none;
    /*清除默认背景 */
    background-color: transparent;
    font-size: 17px;
  }
}

.otherLogo {
  width: 70%;
  margin: 30px auto 0px;
  display: flex;
  justify-content: space-evenly;

  img {
    width: 35px;
    height: 35px;
  }
}

.lineBox {
  width: 90%;
  margin: 20px auto 10px;
  display: flex;
  white-space: nowrap;
  // overflow: hidden;
  height: 20px;
  line-height: 35px;

  .lineOr {
    margin: 0 5px;
    font-size: 15px;
  }

  .line {
    width: 100%;
    border-bottom: 1px solid #bbbbbb;
  }
}

.loginData {
  width: 90%;
  margin: 30px auto;
}

::v-deep .el-form-item__content {
  margin-left: 0px !important;
  display: flex;
  flex-wrap: nowrap;
}

::v-deep .borderZero {
  border-top-left-radius: 0px !important;
  border-bottom-left-radius: 0px !important;

  input {
    border-top-right-radius: 0px !important;
    border-bottom-right-radius: 0px !important;
  }
}

::v-deep .captchaBtn {
  width: 40%;
  background-color: #202123;
  border-color: #202123;
}

.loginBtn {
  width: 100%;
  // height: 20px;
  line-height: 40px;
  height: 40px;

  .loginBtn_img {
    width: 20px;
    height: 20px;
    // background-color: #fff;
    margin-right: 5px;
  }
}

.forget {
  margin: 0px auto 30px;
  text-align: center;
  font-size: 17px;
  border: 0;
  outline: none;
  /*清除默认背景 */
  background-color: transparent;
  font-size: 17px;
}

.resetTitle {
  margin: 100px 0px;
}

@media screen and (min-width: 600px) {
  .logoImg {
    height: 4rem;
  }

  .loginBox {
    width: 400px;
    height: auto;
    border-radius: 10px;
    position: fixed;
    left: 0;
    right: 0;
    top: 18%;
    margin: 0 auto;
    z-index: 9999;
  }

  .resetTitle {
    margin: 40px 0px;
  }
}

.message-wrap {
  z-index: 19998 !important;
}
.iframe-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.iframe {
  width: 585px;
  height: 525px;
  border: 0;
}

.cancel-button {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 10px;
  color: #000000;
  border: 0;
  background-color: white;
  cursor: pointer;
}

</style>
